package mobile.TheOldRepublic.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import mobile.TheOldRepublic.R;
import mobile.TheOldRepublic.util.Constants;
import mobile.TheOldRepublic.util.Utils;

import com.explodingzombie.util.GeneralUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class WebViewActivity extends Activity {
	
	private WebViewWrapper webview = null;
	private String url = null;
	private boolean loginOpen = false;
	
	// TODO Change to something that saves between runs. LP
	private static String username = null;

	@Override
    protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		webview = new WebViewWrapper(this);
		if(savedInstanceState != null){
			webview.restoreState(savedInstanceState);
		}
		
//		if(loginOpen) openLoginWindow(this);
		Bundle extras = getIntent().getExtras();
		if(extras != null)
			url = extras.getString(Constants.KEY_URL);
		if(GeneralUtils.isEmpty(url)){
			this.finish();
			return;
		}
		
		System.out.println("Loading URL "+url);
		setContentView(webview);
		ProgressDialog pd = ProgressDialog.show(this, Constants.PROGRESS_TEXT_WV, Constants.PROGRESS_SUBTEXT_WV, true, false);
		webview.setProgressDialog(pd);

		webview.loadUrl(url);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState){
		webview.saveState(outState);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event){
		if((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()){
			webview.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private OnMenuItemClickListener refreshListener = new OnMenuItemClickListener() {
		@Override
		public boolean onMenuItemClick(MenuItem item) {
			// We had images that were stuck having not been loaded.
			// To fix I'm clearing the cache on reload. LP
			webview.clearCache(true);
			webview.loadUrl(url);
			return true;
		}
	};
	    
    @Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		final Context context = this;
		menu.clear();
		
		MenuItem refresh = menu.add("Refresh");
		refresh.setIcon(android.R.drawable.ic_menu_rotate);
		refresh.setOnMenuItemClickListener(refreshListener);
		
		MenuItem login = menu.add("Login");
		login.setIcon(android.R.drawable.presence_online);
		login.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				openLoginWindow(context);
				return true;
			}
		});
		
		MenuItem sendDebug = menu.add("Send HTML to Debug");
		sendDebug.setIcon(android.R.drawable.ic_menu_send);
		sendDebug.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				try{
					String outHtml = webview.getDebuggingHtml();
					Intent i = new Intent(Intent.ACTION_SEND);
					i.setPackage("com.google.android.gm");
					i.setType("text/html");
					i.putExtra(Intent.EXTRA_EMAIL, new String[]{"ittr-bugs@explodingzombie.com"});
					i.putExtra(Intent.EXTRA_SUBJECT, "ITTR Test HTML");
					i.putExtra(Intent.EXTRA_TEXT, "<!-- "+url+" -->"+outHtml);
					context.startActivity(i);
				}catch(Exception e){
					e.printStackTrace();
					Toast.makeText(context, "Failed to send email.", Toast.LENGTH_LONG).show();
				}
				return true;
			}
		});
				
		return true;
	}
    
    public void openLoginWindow(Context context){
    	try{
			LayoutInflater inflater = (LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
	        View layout = inflater.inflate(R.layout.login, null, false);
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setView(layout);
			final AlertDialog dialog = builder.show();
			loginOpen = true;

			// If there is no username, try to deserialize username that was saved in previous run. LP
			final File usernameSer = new File(Utils.getAppDirectory(), Constants.FILENAME_USERNAME);
			if(GeneralUtils.isEmpty(WebViewActivity.username) && usernameSer.exists()){
				ObjectInputStream objStream = null;
				try{
					objStream = new ObjectInputStream(new FileInputStream(usernameSer));
					username = (String)objStream.readObject();
				}catch(Exception e){
				}finally{
					if(objStream != null) try{ objStream.close(); } catch(Exception e){}
				}
			}
			EditText user = (EditText)layout.findViewById(R.id.username);
			if(! GeneralUtils.isEmpty(WebViewActivity.username))
				user.setText(WebViewActivity.username);
			user.addTextChangedListener(new TextWatcher(){
				@Override
                public void afterTextChanged (Editable s){
					String value = s.toString();
					if(GeneralUtils.isEmpty(WebViewActivity.username) ||
							!WebViewActivity.username.equals(value)){
						WebViewActivity.username = value;
						// Serialize username to disk so it can be loaded on subsequent runs. LP
						ObjectOutputStream objStream = null;
						try{
							objStream = new ObjectOutputStream(new FileOutputStream(usernameSer));
							objStream.writeObject(WebViewActivity.username);
						}catch(Exception e){
							Log.w(getClass().getSimpleName(), "Unable to save username data.");
							e.printStackTrace();
						}finally{
							if(objStream != null) try{ objStream.close(); } catch(Exception e){}
						}
					}
                }
                @Override
                public void beforeTextChanged(CharSequence s,int start,int count,int after){}
                @Override
                public void onTextChanged(CharSequence s,int start,int before,int count){} 
            });
			
			Button btn = (Button)layout.findViewById(R.id.login_cancel_btn);
			btn.setOnClickListener(new View.OnClickListener(){
				@Override
				public void onClick(View view){
					dialog.cancel();
					loginOpen = false;
				}
			});
			
			btn = (Button)layout.findViewById(R.id.login_btn);
			btn.setOnClickListener(new View.OnClickListener(){
				@Override
				public void onClick(View view){
					EditText data = (EditText)dialog.findViewById(R.id.password);
					CharSequence pwd = data.getText();
					data = (EditText)dialog.findViewById(R.id.username);
					CharSequence user = data.getText();
					dialog.dismiss();
					webview.login(user, pwd);
				}
			});
			
			btn = (Button)layout.findViewById(R.id.login_forgot_btn);
			btn.setOnClickListener(new View.OnClickListener(){
				@Override
				public void onClick(View view){
					dialog.dismiss();
					webview.forgotPassword();
				}
			});
		}catch(Exception e){
			e.printStackTrace();
		}
    }
}